<template>
	<!-- 设备列表 -->
	<view class="page-content">
		<view class="page-body">
			<view v-if="datalist && datalist.length > 0 ">
				<block v-for="(item,index) in datalist" :key="index">
					<view class="list-li" @click="connetBlue(0,index)">
						<view class="list-li-l">
							<view class="list-li-l-tit">{{i18n.pair.pairName}}：{{item.mac_name}}</view>
							<text class="list-li-l-mon"
								:style="{background:item.model_type==='1'?'#D70000':'#00CD8B'}">{{item.model_type==='1'?i18n.pair.jihuoban:i18n.pair.tongyongban}}</text>
						</view>
						<view class="list-li-r">
							<view class="icons icon-gengduo"></view>
						</view>
					</view>
				</block>
			</view>
			<!--无数据-->
			<empty v-else no-full type="noData"></empty>
		</view>
		
		
		<!-- <view class="topTitle">已发现 {{deviceNum}} 个蓝牙设备</view>
		<scroll-view scroll-y scroll-with-animation  class="deviceListWrap">
		  <view  @change="onChange" accordion="true">
		      <block :title="item.name" v-for="(item,index) in deviceList" :key="index">
		        <view slot="title">{{item.name}}</view>
		        <view>信号强度：{{item.RSSI}}dBm({{(100 + item.RSSI)}}%)</view> 
		        <view>UUID：{{item.deviceId}}</view> 
		        <view class='concatBtn'><button size="mini" type="primary" @click="connetBlue(0,index)" >连接设备</button></view>  
		      </block>
		  </view>
		</scroll-view> 
		<view class="connectedStatus">
				<button size="defult" type="primary" @click="initBluetoothModule" style="margin: 20upx 0;">开始扫描</button>
				<button size="defult" type="defult" @click="closeBluetoothAdapter" style="margin: 20upx 0;">停止扫描</button>
		  <view v-if="connected" class="nowConcat">已连接到：{{connectedName}}</view> 
		  <view  v-if="prevConnected">
		    <view  class="npConcat">上次连接：{{pDeviceInfo.name}}</view> 
		    <button size="defult" type="defult" @click="connetBlue(1,-1)">直接连接</button>
		  </view> 
				 <view v-if="connected" class="nowConcat">
					<button size="defult" type="defult" @click="getBLEDeviceServices" style="margin: 20upx 0;">测试打印</button>
				</view> 
		</view> -->
	</view>
</template>

<script>
	import {
		getMacLists,
	} from '@/common/api.js';
	export default {
		components: {},
		data() {
			return {
				deviceList:[], //所有的蓝牙设备
				datalist:[], //需要的蓝牙设备
				connected:true,
				connectedName:'',
				prevConnected:false,
				pDeviceInfo:{}, //上次连接
				deviceId:'',
				serviceId:'',
				characteristics:'',
			};
		},
		computed: {
			i18n() {
				return this.$t('message');
			}
		},
		onLoad() {
			//初始蓝牙模块
			this.pDeviceInfo = uni.getStorageSync('deviceInfo');
			if(!!this.pDeviceInfo){
				this.prevConnected = true;
			}
			this.initBluetoothModule()
		},
		methods:{
			initBluetoothModule(){
				//初始蓝牙模块
				uni.openBluetoothAdapter({
				  success:res=> {
					this.searchBlueList();
				  },
				  fail:err=>{
					console.log(err)
				  }
				})
			},
			searchBlueList(){
				//开启蓝牙搜索
				uni.startBluetoothDevicesDiscovery({
					success:res=> {
						setTimeout(()=>{
							this.getBlueList();
							  uni.showToast({
								title: '开启成功',
								icon: 'success',
								duration: 1000
							});
						},1000);
					},
				})
			},
			getBlueList(){
				//获取搜索列表
				uni.getBluetoothDevices({
				  success:res=> {
					let data = res.devices
					let tempList=[];
					data.map(device=>{
					  if(!!device.localName){
						tempList.push(device)
					  }
					});
					this.deviceList = tempList;
					console.log(3,this.deviceList)
					this.listenBluetooth();
				  }
				});
			},
			listenBluetooth(){
				let tempList =this.deviceList;
				//监听蓝牙搜索
				uni.onBluetoothDeviceFound((res) => {
				  let flag = false;
				  let arr = []
				  res.devices.forEach(device => {
					if(!!device.localName){
					  tempList.push(device)
					  arr.push(device.deviceId)
					  console.log(22,arr)
					  flag =true;
					}
				  })
				  if(flag){
					this.deviceList = tempList;
					
					let mac = arr.join(',');
					console.log(4,arr)
					console.log(44,mac)
					//接口-获取mac码列表
					getMacLists({mac:mac}).then(res2 =>{
						console.log(5,res2)
						if(res2.code === 2000){
							_self.datalist = res2.data.success;
						}
					})
				  }
			   })
			},
			//连接蓝牙设备
			connetBlue(type,index){
				let _self = this;
				let deviceIndex = index;
				let deviceInfo = this.datalist[deviceIndex];
				if(this.prevConnected && type == 1){
				  deviceInfo = this.pDeviceInfo;
				} 
				let dId = deviceInfo.mac;
				uni.showLoading({
				  title: '正在连接...', //提示的内容,
				  mask: true
				});
				//连接蓝牙-低功耗蓝牙
				uni.createBLEConnection({
				  deviceId: dId,//设备id
				  success: res=> {
					uni.hideLoading();	
					if(res.errCode == 0){
					  _self.connected = true;
					  _self.connectedName = deviceInfo.name;
					  uni.setStorageSync('deviceInfo',deviceInfo);
					  _self.deviceId = dId;
					  uni.showToast({
						title: '连接成功',
						icon: 'success',
						duration: 1000
					});
					}
					uni.stopBluetoothDevicesDiscovery({
					  success: res => {
						console.log('连接蓝牙成功之后关闭蓝牙搜索');
					  }
					})
				  },
				  fail:err=>{
					uni.showToast({
						title: '连接失败！', 
						icon: 'none', 
						duration: 2000
					  });
				  }
				})
			},
			getBLEDeviceServices(){
				//获取服务
				uni.showLoading({
				  title: '正在打印...', //提示的内容,
				  mask: true
				});
				let deviceId = this.deviceId;
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {	
					  for (let i = 0; i < res.services.length; i++) {
						if (res.services[i].isPrimary) {
						  this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
						}
					  }
					},
					fail: (res) => {
					  uni.hideLoading();
					  console.log("获取蓝牙服务失败：" + JSON.stringify(res))
					}
				})
			},
			//获取单个服务的特征值(characteristic)
			getBLEDeviceCharacteristics(deviceId, serviceId){
				if(!!this.characteristics && !!this.serviceId){
					this.PrintStr();
					return;
				}
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						uni.hideLoading();
						for (let i = 0; i < res.characteristics.length; i++) {
							let item = res.characteristics[i];
							if (item.properties.write && !this.serviceId) {
								this.serviceId = serviceId;
								this.characteristics = item.uuid;
								this.PrintStr();
							}
						}
					},
					fail(res) {
					uni.hideLoading();
					console.error('获取特征值失败：', res)
					}
				})
			},
			PrintStr() {
				const buf = Buffer.from("this is test content!");
				var bufferstr = buf.buffer; 
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristics,
					value: bufferstr,
					success: function (res) {
						 uni.hideLoading();
					},
					fail: function (res) {
						console.log("数据发送失败:" + JSON.stringify(res))
					},
					complete: function (res) {
						
					},
				})
			},
			closeBluetoothAdapter(){
				uni.closeBluetoothAdapter({
				  success: res => {
					console.log('关闭蓝牙适配器');
				  }
				});
			},
		},
		onPullDownRefresh() {
			console.log('refresh');
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onUnload() {
		  this.closeBluetoothAdapter();
		}
	}
</script>

<style lang="scss">
	.page-content {
		width: 100vw;
		background: $uni-bg-color;
		color: $font-color-w;
		padding: $page-row-spacing;
		height: 100%;
	}
	
	.page-body {
		height: 100%;
		display: flex;
		flex-direction: column;
	
		.list-li {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: $page-row-spacing;
			background: $uni-bg-box-color;
			box-shadow: 0rpx 2rpx 9rpx 0rpx rgba(0, 0, 0, 0.44);
			border-radius: 20rpx;
			margin-bottom: 40rpx;
			color: #fff;
	
			.list-li-l {
				display: flex;
				font-size: 28rpx;
	
				.list-li-l-tit {
					margin-right: 20rpx;
				}
	
				.list-li-l-mon {
					height: 40rpx;
					border-radius: 20rpx;
					padding: 0 16rpx;
					font-size: 20rpx;
					font-weight: 400;
					line-height: 40rpx;
					margin-left: 16rpx;
				}
			}
		}
	}
	
	
	
.topTitle{font-size: 15px;padding: 5px;color: #999;text-align: center;}
.deviceListWrap{height: calc(100vh - 160rpx); }
.connectedStatus{position: fixed;bottom: 30rpx;left: 15%;width: 70%;text-align: center;border-top: 1px solid #eee;}
.concatBtn{text-align: center;margin: 30rpx 0;}
.nowConcat {margin: 5px 0;color: #333;}
.npConcat{margin: 5px 0;color: #999;}
</style>